package main

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"fmt"
	"github.com/tjfoc/gmsm/sm2"
	sm509 "github.com/tjfoc/gmsm/x509"
)

var gConfig *Config
var gSm2PrivKey *sm2.PrivateKey
var gHySm2PubKey *sm2.PublicKey
var gRsaPrivKey *rsa.PrivateKey
var gHyRsaPubKey *rsa.PublicKey

func loadPrivateKey() {
	var err error

	if gConfig.Sm2Keys.Format == "pkcs8" {
		privData, err := base64.StdEncoding.DecodeString(gConfig.Sm2Keys.PrivateKey)
		if err != nil {
			panic(err)
		}
		gSm2PrivKey, err = Read_sm2_private_key_asn1(privData, "")
		if err != nil {
			panic(err)
		}
	} else {
		gSm2PrivKey, err = sm509.ReadPrivateKeyFromHex(gConfig.Sm2Keys.PrivateKey)
		if err != nil {
			panic(err)
		}
	}
	fmt.Printf("Sm2 Private key: %064x, pub (%064x, %064x)\n", gSm2PrivKey.D, gSm2PrivKey.X, gSm2PrivKey.Y)

	block, err := base64.StdEncoding.DecodeString(gConfig.RsaKeys.PrivateKey)
	if err != nil {
		panic(err)
	}
	priKey, err := x509.ParsePKCS8PrivateKey(block)
	if err != nil {
		panic(err)
	}
	gRsaPrivKey = priKey.(*rsa.PrivateKey)

	fmt.Printf("Rsa Private key: D=%x, pub (N=%x, E=%x)\n", gRsaPrivKey.D, gRsaPrivKey.N, gRsaPrivKey.E)
}

func loadHyPublicKey() {
	var err error

	//fmt.Printf("sm2 public key: %s\n", gConfig.Sm2Keys.HyPublicKey)

	if gConfig.Sm2Keys.Format == "pkcs8" {
		pubData, err := base64.StdEncoding.DecodeString(gConfig.Sm2Keys.HyPublicKey)
		if err != nil {
			panic(err)
		}
		gHySm2PubKey, err = Read_sm2_public_pem_data(pubData)
		if err != nil {
			panic(err)
		}
	} else {
		gHySm2PubKey, err = sm509.ReadPublicKeyFromHex(gConfig.Sm2Keys.HyPublicKey)
		if err != nil {
			panic(err)
		}
	}
	fmt.Printf("HY public key: (%064x, %064x)\n", gHySm2PubKey.X, gHySm2PubKey.Y)

	block, err := base64.StdEncoding.DecodeString(gConfig.RsaKeys.HyPublicKey)
	if err != nil {
		panic(err)
	}
	pubKey, err := x509.ParsePKIXPublicKey(block)
	if err != nil {
		panic(err)
	}
	gHyRsaPubKey = pubKey.(*rsa.PublicKey)

	fmt.Printf("Hy Rsa public key: N=%x, E=%x\n", gHyRsaPubKey.N, gHyRsaPubKey.E)
}

func main() {
	fmt.Println("开始执行程序")
	gConfig = ReadConfig()
	fmt.Printf("listen: %v\n", gConfig.Listen)
	//fmt.Printf("hypub: %v\n", gConfig.HySm2PubKeyHex)
	//fmt.Printf("private: %v\n", gConfig.Sm2PrivateKeyHex)

	Execute()
	fmt.Println("正常退出程序")
}
